package com.lengmomo.games.websocket;

import cn.hutool.json.JSONUtil;
import com.lengmomo.games.pojo.po.ChessMessage;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: lengmomo
 * @create: 2021/9/15
 **/
@Data
@ServerEndpoint(value = "/JWS")
//@ServerEndpoint(value = "/cws", configurator = WebSocketConfig.class)
// value:websocket名称用于客户连接 configurator:设置配置器
@Component
public class JqWebSocketServer {

    private static Map<String, Session> onlineUsers = new ConcurrentHashMap<>();//存放在线用户session方便交流
    private static Map<String,String> playing = new ConcurrentHashMap<>();

    /**
     * 用户连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineUsers.put(session.getId(), session);
        //给连接用户发一条消息保存他的id
        session.getAsyncRemote().sendText(JSONUtil.toJsonStr(new ChessMessage().setType("0").setMsg(session.getId())));
    }

    /**
     * 用户关闭连接
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        if(playing.containsKey(session.getId())){
            String s = playing.get(session.getId());
            ChessMessage msg = new ChessMessage().setType("4").setFrom(session.getId());
            onlineUsers.get(s).getAsyncRemote().sendText(JSONUtil.toJsonStr(msg));
            playing.remove(s);//移除对局
            playing.remove(session.getId());//移除对局
        }
        onlineUsers.remove(session.getId());
    }

    /**
     * 客户端发消息过来
     *
     * @param message 消息内容
     * @param session 客户端session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        ChessMessage msg = JSONUtil.toBean(message, ChessMessage.class);
        switch (msg.getType()){
            case "1"://返回对局id
            case "5"://移动棋子
            case "6"://对战前准备数据
                onlineUsers.get(msg.getTo()).getAsyncRemote().sendText(JSONUtil.toJsonStr(msg));
                break;
            case "2": //2接受对战
            case "3"://3拒绝对战
                if(StringUtils.equals(msg.getType(),"2")){
                    playing.put(msg.getFrom(),msg.getTo());
                    playing.put(msg.getTo(),msg.getFrom());
                }
                onlineUsers.get(msg.getFrom()).getAsyncRemote().sendText(JSONUtil.toJsonStr(msg));
                break;
            default: break;
        }
    }


    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();

    }

    /**
     * 开放获取用户列表 用于controller调用
     * @return
     */
    public synchronized Map<String, Session> getOnlineUsers() {
        return onlineUsers;
    }
}
